package com.alvin.demo.utils;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class MinaResult extends IoHandlerAdapter {
    private String content = "";
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * 客户端接收到返回消息后的处理方法
     */
    @Override
    public void messageReceived(IoSession iosession, Object message) { //客户端收到消息
        IoBuffer buf = (IoBuffer) message;
        byte[] bytes = new byte[buf.limit()];
        buf.get(bytes, buf.position(), buf.limit());
        this.content = bytes2HexString(bytes);
    }

    /**
     * 从字节数组解密并且将其转化为字符串
     * @param bytes 字节数组
     * @return 字符串
     */
    private static String bytes2HexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF); // 将 byte转换为 16进制字符串
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex.toUpperCase()); // 转成大写
            if (i != bytes.length - 1){
                hexString.append(" ");
            }
        }
        return hexString.toString();
    }
}
